<template>
  <div
    :class="$route.query.processInstanceId ? 'flow-container' : 'app-container'"
  >
    <div
      v-show="
        !modifyInfo.visible &&
        !detailInfo.visible &&
        !detailListInfo.visible &&
        !modifyLossInfo.visible &&
        !$route.query.processInstanceId
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <new-page-filter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </new-page-filter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <new-page-filter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-print>
            <el-button @click="print()">打印</el-button>
          </template>
          <template v-slot:filter-download>
            <el-button @click="exportExcel()">导出excel</el-button>
          </template>
          <template v-slot:filter-approve>
            <el-button :disabled="!canApprove" @click="approveBatch()"
              >批准</el-button
            >
          </template>
        </new-page-filter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @sortChange="sortChange"
        @handleEvent="handleEvent"
        @pageInfo="pageInfo"
        :row-class-name="tableRowClassName"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
      </table-container>
    </div>

    <order-modify
      ref="modifyRef"
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <modify-loss
      ref="modifyRef"
      v-if="modifyLossInfo.visible"
      v-model:visible="modifyLossInfo.visible"
      :id="modifyLossInfo.id"
      :lossId="modifyLossInfo.lossId"
      :lossNo="modifyLossInfo.lossNo"
      :title="modifyLossInfo.title"
      :type="''"
      :inventoryLocation="modifyLossInfo.inventoryLocation"
      :flowFormType="flowFormType"
      @returnModify="returnModify"
    />
    <order-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
    <SelectLoss
      v-if="assetLossInfo.visible"
      v-model:show-dialog="assetLossInfo.visible"
      :highlight-row="true"
      :check-box="false"
      :save-empty="false"
      @callback="selectLossBack"
    ></SelectLoss>
  </div>
</template>

<script setup name="assetDeal">
import {
  assetDealCustomizeListPage,
  deleteAssetDeal,
  submitAssetDeal,
  auditAssetDeal,
  auditBatchAssetDeal,
  rejectAssetDeal,
  refuseAssetDeal,
  revokeAssetDeal,
  salesReviewAssetDeal,
  excelAssetDealList,
  printAssetDealList,
  getAssetDealById,
} from '@/api/asset.js'
import { getBusinessKeyById } from '@/api/flowable'
import { fatchTemplateByCode } from '@/api/base'
import { getDepotAll } from '@/api/core'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import OrderModify from './modify'
import OrderDetail from './details'
import SelectLoss from './selectLoss'
import ModifyLoss from './modifyLoss'

const detailList = defineAsyncComponent(() => import('./detailList'))
const { proxy } = getCurrentInstance()
const props = defineProps(['id'])

const dialogInfo = ref({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    {
      label: '关闭',
      event: handleClose,
      show: true,
    },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
  },
  searchList: [],
  searchBtn: [
    {
      type: 'button',
      label: '搜索',
      event: search,
    },
    {
      type: 'button',
      label: '高级查询',
      event: advancedSearchShow,
    },
    {
      type: 'button',
      label: '重置',
      event: clearSearch,
    },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('assetDeal:add'),
    },
    {
      type: 'slot',
      value: 'approve',
      show:
        proxy.$permission('assetDeal:approve') &&
        proxy.$store.state.permission.systemConfig.allow_assets_deal_approval ==
          1,
    },
    {
      type: 'slot',
      value: 'download',
      show: proxy.$permission('assetDeal:download'),
    },
    {
      type: 'button',
      label: '盘亏导入',
      value: 'assetDealImport',
      event: showAssetLoss,
      show: proxy.$permission('assetDeal:assetDealImport'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('assetDeal:printOrderList'),
    },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('assetDeal:submit'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 6
        },
      },
      {
        label: '修改',
        event: update,
        show: proxy.$permission('assetDeal:update'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 6
        },
      },
      {
        label: '批准',
        event: (row) => btnFlow(row, 'approve'),
        show: proxy.$permission('assetDeal:approve'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '驳回',
        event: (row) => btnFlow(row, 'reject'),
        show: proxy.$permission('assetDeal:reject'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '拒绝',
        event: (row) => btnFlow(row, 'refuse'),
        show: proxy.$permission('assetDeal:refuse'),
        ifRender: checkIfRenderBtnFlow,
      },
      {
        label: '撤回',
        event: recall,
        show: proxy.$permission('assetDeal:recall'),
        ifRender: checkIfRenderRecall,
      },
      {
        label: '销审',
        event: salesReview,
        show: proxy.$permission('assetDeal:salesReview'),
        ifRender: checkIfRenderSalesReview,
      },
      {
        label: '删除',
        event: remove,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('assetDeal:delete'),
        ifRender: function (row) {
          return row.status === 1 || row.status === 6
        },
      },
    ],
  },
})
const modifyInfo = ref({
  visible: false,
  id: '',
  title: '',
})
const detailListInfo = ref({
  visible: false,
})
const detailInfo = ref({
  visible: false,
  id: '',
})
const preferenceInfo = ref({
  visible: false,
})
const advancedSearchInfo = ref({
  visible: false,
  data: {},
})
const assetLossInfo = ref({
  visible: false,
})
const modifyLossInfo = ref({
  visible: false,
  id: '',
  lossId: '',
  title: '',
  lossNo: '',
  inventoryLocation: '',
})
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const flowFormType = ref('')

const canApprove = computed(() => {
  return (
    tableInfo.value.selections.length &&
    tableInfo.value.selections.filter((item) => item.status == 2).length ===
      tableInfo.value.selections.length
  )
})
const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'assetDeal' && el.url === val.url) {
                detailListInfo.value.visible = false
                modifyInfo.value.visible = false
                modifyLossInfo.value.visible = false
                detailInfo.value.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailInfo.value.visible = true
                    detailInfo.value.id = val.businessId
                    sessionStorage.setItem('storeRowId', val.businessId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
onMounted(() => {
  if (proxy.$route.query.processInstanceId) {
    getAssetDealById(props.id).then((resp) => {
      if (resp && resp.success) {
        toModify(resp.data)
        flowFormType.value = 'defaultFlowType'
      }
    })
  } else {
    flowFormType.value = ''
  }
  setData()
})
// 外部流程组件也需调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  proxy.$refs['modifyRef'].save(isSaveAndSubmit, obj)
}
function update(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetDeal',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        toModify(row)
      }
    }
  })
}
function toModify(row) {
  if (row.sourceType === 109) {
    modifyLossInfo.value.visible = true
    modifyLossInfo.value.id = row.id
    modifyLossInfo.value.lossId = row.sourceId
    modifyLossInfo.value.lossNo = row.sourceOrderNo
    modifyLossInfo.value.inventoryLocation = row.position
    modifyLossInfo.value.title = '修改'
  } else {
    modifyInfo.value.id = row.id
    modifyInfo.value.title = '修改'
    modifyInfo.value.visible = true
  }
}
function setData() {
  let obj = {
    depotName: {
      label: '仓库',
      value: 'depotName',
      asValue: 'depotId',
      componentType: 'slip-select',
      query: {
        depotAuth: 'id',
        status: 1,
        useTypeId: '2',
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    typeValue: {
      label: '类型',
      value: 'typeValue',
      asValue: 'type',
      componentType: 'select-model',
      code: 'asset_Deal_type',
      show: false,
      hidden: true,
    },
    statusValue: {
      label: '状态',
      value: 'statusValue',
      asValue: 'status',
      componentType: 'select-model',
      code: 'asset_deal_order_status',
      show: false,
      hidden: true,
      multiple: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  })
  getCustomize()
}
function handleClose() {
  dialogInfo.value.visible = false
}
function pageInfo(obj) {
  page.value = obj
}
//盘亏弹窗
function showAssetLoss() {
  assetLossInfo.value.visible = true
}
function selectLossBack(data) {
  if (data && data.id) {
    modifyLossInfo.value.visible = true
    modifyLossInfo.value.id = ''
    modifyLossInfo.value.lossId = data.id
    modifyLossInfo.value.lossNo = data.orderNo
    modifyLossInfo.value.inventoryLocation = data.inventoryLocation
    modifyLossInfo.value.title = '新增'
  }
}
// 销审
function checkIfRenderSalesReview(row) {
  return (
    row.status === 9 &&
    proxy.$store.state.permission.systemConfig.allow_assets_deal_approval != 0
  )
}
// 撤回
function checkIfRenderRecall(row) {
  return (
    row.status === 2 ||
    (row.status === 9 &&
      proxy.$store.state.permission.systemConfig.allow_assets_deal_approval ===
        0)
  )
}
// 批准/驳回/拒绝 按钮展示
function checkIfRenderBtnFlow(row) {
  return (
    proxy.$store.state.permission.systemConfig.allow_assets_deal_approval ==
      1 && row.status === 2
  )
}
//提交
function submit(row = undefined) {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetDeal',
    orderId: row.id,
  }
  submitAssetDeal(data).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 审批/拒绝/驳回按钮审批原因弹窗
function btnFlow(row, code, isBatch) {
  const currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'approve') {
    currentBtnFlow.api = isBatch ? auditBatchAssetDeal : auditAssetDeal
    const data = isBatch
      ? {
          orderIds: row.ids,
        }
      : {
          orderId: row.id,
        }
    currentBtnFlow.api(data).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
    return
  } else if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAssetDeal
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAssetDeal
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          getList()
        }
      })
    })
}
// 撤回
function recall(row = undefined) {
  revokeAssetDeal([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 销审
function salesReview(row) {
  salesReviewAssetDeal([row.id]).then((res) => {
    if (res && res.success) {
      getList()
      proxy.$message.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      proxy.$message.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
// 批量批准
function approveBatch() {
  let ids = tableInfo.value.selections.map((item) => item.id)
  btnFlow(
    {
      ids,
    },
    'approve',
    true
  )
}
function checkConfirm() {
  if (dialogInfo.value.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false
  dialogInfo.value.msg = ''
}
function exportExcel() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'excel'
  dialogInfo.value.msg = '请选择数据导出范围'
  dialogInfo.value.btList[1].label = '导出'
  dialogInfo.value.flag = true
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogInfo.value.flag,
  }
  excelAssetDealList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
async function print() {
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
  dialogInfo.value.flag = true
}
//打印
function printList() {
  fatchTemplateByCode({
    resourceCode: 'assetDeal:printOrderList',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.value.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: flag,
  }
  printAssetDealList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function returnModify() {
  if (modifyInfo.value.id) {
    getList()
  } else {
    search()
  }
}
async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {}
  filterInfo.value.query.queryDtoList = [...obj.queryDtoList]
  advancedSearchInfo.value.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryDtoList = []
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
//删除
function remove(row) {
  deleteAssetDeal([row.id]).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//创建
function create() {
  modifyInfo.value.id = ''
  modifyInfo.value.title = '新增'
  modifyInfo.value.visible = true
}
//展示明细
function showDetail(row) {
  getBusinessKeyById({
    businessKey: row.orderNo,
    businessType: 'assetDeal',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.value.id = row.id
        detailInfo.value.visible = true
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.value.data = {}
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  )
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'assetDealOrderList-com.slip.spd.entity.vo.asset.AssetDealOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.searchList = searchInfo.searchList
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.value.api = assetDealCustomizeListPage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped>
.flow-container {
  height: calc(100vh - 164px);
}
</style>
